// Hide next button
this.hideNextButton();

// Stash location of question
var that = this;

// Set colors here
var light_color = "#f96f67";

// Create stash for coin-placement order
var coin_order = [];

// Set scale labels
var left_label_1 = 'THE';
var left_label_2 = 'LEFT';
var left_label_3 = 'LABEL';

var right_label_1 = 'THE';
var right_label_2 = 'RIGHT';
var right_label_3 = 'LABEL';

// Define visual parameters
var plot_width = 800,
	plot_height = 600,
	margin = {top: 30, right: 30, bottom: 30, left: 110}, // Plot skews left
    width = plot_width - margin.left - margin.right,
    height = plot_height - margin.top - margin.bottom,
	v_space = 18,

    bins = 11,
    bin_width = (width / bins),
    bin_height = 250,
    tokens = 20,
	coin_height = (bin_height) / tokens - 1,
    used_tokens = 0,

	dist_title_y = 15,
	dist_axis_text_y = dist_title_y + v_space + bin_height + v_space,

    submit_button_width = 100,
    button_height = 25,

	title_font_size = 20,
	axis_text_font_size = 18,

    dist_tracker = {};

var svg = d3.select('#dist_body')
    .append('svg')
    .attr("preserveAspectRatio", "xMinYMin meet")
  	.attr("viewBox", "0 0 " + (plot_width * 1.1) + " " + (plot_height * 1.1))
  	.style('display', 'inline-block')
	.style('position', 'absolute')
	.style('top', 0)
	.style('left', 0)
    .append('g')
    .attr('transform',"translate(" + margin.left + "," + margin.top + ")");

var coins = svg.append('g'),
    bars = svg.append('g');

// Add plot title
var plot_title = svg.append('text')
    .attr('y', dist_title_y)
    .attr('x', width / 2)
    .attr('text-anchor', 'middle')
    .text('Tokens left: ' + tokens)
	.style('user-select',' none')
    .style('font-size', title_font_size)
    .classed('texts', true);

// Add submit button
/// Container
var end_g = svg.append('g')
  .attr('opacity', 0);

/// Visible button
end_g.append('rect')
  .attr('x', (width / 2) - (submit_button_width / 2))
  .attr('width', submit_button_width)
  .attr('y', dist_axis_text_y + (v_space * 4) + button_height + v_space)
  .attr('height', button_height)
  .attr('rx', 10)
  .attr('fill', 'green');

/// Text
end_g.append('text')
  .attr('x', width / 2)
  .attr('y', dist_axis_text_y + (v_space * 4) + button_height + v_space + (button_height / 1.3))
  .attr('fill', 'white')
  .attr('text-anchor', 'middle')
  .style('user-select', 'none')
  .attr('font-size', title_font_size)
  .text('Submit');

/// Active invisible layer
var end_button = end_g.append('rect')
    .attr('x', (width / 2) - (submit_button_width / 2))
    .attr('width', submit_button_width)
    .attr('y', dist_axis_text_y + (v_space * 4) + button_height + v_space)
    .attr('height', button_height)
    .attr('rx', 10)
    .attr('opacity', 0)
    .on('click', return_data);

// Draw background and scale points
for (let i = 0; i < bins; i++){
    // Shaded regions denoting columns
    coins.append('rect')
        .attr('x', i * bin_width)
        .attr('width', bin_width - 1)
        .attr('y', dist_title_y + v_space)
        .attr('height', bin_height + (v_space * 1.2)) // Extend past text
        .attr('fill', 'grey')
        .attr('fill-opacity', i % 2 === 0 ? 0 : 0.1)
        .attr('id', 'bin-' + i)
        .attr('class', 'bin');

    // I think a container for coin placement?
    bars.append('rect')
        .attr('x', i * bin_width)
        .attr('width', bin_width - 1)
        .attr('y', dist_title_y + v_space)
        .attr('height', bin_height)
        .attr('fill-opacity', 0)
        .attr('id', 'bin-' + i)
        .attr('class', 'bin');

    // Scale points text
    bars.append('text')
      .attr('x',(i * bin_width) + (bin_width / 2))
      .attr('y', dist_axis_text_y)
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
      .text(i);

    // Remove buttons
    /// Text
    bars.append('text')
      .attr('x', (i * bin_width) + (bin_width / 2))
      .attr('y', dist_axis_text_y + (v_space * 4) + (button_height / 1.5))
      .attr('text-anchor', 'middle')
      .attr('font-size', axis_text_font_size - 4)
      .attr('stroke', 'red')
   	  .style('user-select', 'none')
      .text("remove");

    /// Button
    bars.append('rect')
        .attr('x', i * bin_width)
        .attr('width', bin_width)
        .attr('y', dist_axis_text_y + (v_space * 4))
        .attr('height', button_height)
        .attr('fill', 'white')
        .attr('fill-opacity', 0)
        .attr('stroke-width', '1')
        .attr('rx', 10)
        .attr('stroke', 'black')
        .attr('id', 'bin-' + i)
        .attr('class', 'deleter');

    // Tracker
    dist_tracker['bin-'+i] = {'currentY':bin_height+coin_height,'coins':[]};
}

// Add scale labels to perceived distribution
/// Left labels
bars.append('text')
      .attr('x', bin_width / 2)
      .attr('y', dist_axis_text_y + v_space)
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
	  .text(left_label_1);

bars.append('text')
      .attr('x', bin_width / 2)
      .attr('y', dist_axis_text_y + (v_space * 2))
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
	  .text(left_label_2);

bars.append('text')
      .attr('x', bin_width / 2)
      .attr('y', dist_axis_text_y + (v_space * 3))
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
	  .text(left_label_3);

/// Right labels
bars.append('text')
      .attr('x', (10 * bin_width) + bin_width / 2)
      .attr('y', dist_axis_text_y + v_space)
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
	  .text(right_label_1);

bars.append('text')
      .attr('x', (10 * bin_width) + bin_width / 2)
      .attr('y', dist_axis_text_y + (v_space * 2))
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
	  .text(right_label_2);

bars.append('text')
      .attr('x', (10 * bin_width) + bin_width / 2)
      .attr('y', dist_axis_text_y + (v_space * 3))
      .attr('text-anchor', 'middle')
	  .style('user-select', 'none')
	  .style('font-size', axis_text_font_size)
	  .text(right_label_3);

// Allow participant to add coins
d3.selectAll('.bin')
    .on('click',function(d){
        if (used_tokens < tokens){
            var add = d3.select(this);
            var count = dist_tracker[add.attr('id')].coins.length;
            var bin_coin_id = 'cb-'+add.attr('id') + "-" + count;

            coins.append('rect')
                .attr('x',add.attr('x'))
                .attr('width', bin_width - 1)
                .attr('y', dist_tracker[add.attr('id')].currentY)
                .attr('height', coin_height)
                .attr('fill', light_color)
                .attr('stroke-width', 0.5)
                .attr('stroke', 'black')
                .attr('rx', 6)
                .attr('id', bin_coin_id);

            dist_tracker[add.attr('id')].currentY -= coin_height;
            dist_tracker[add.attr('id')].coins.push(bin_coin_id);
			
			// Add token addition to order
			coin_order.push("ADD" + add.attr('id'));
			
            // Increment tokens used
            used_tokens += 1;

            // Update plot title
            plot_title.text('Tokens left: ' + (tokens - used_tokens));

            if (used_tokens === tokens){
              end_g.attr('opacity', 1);
            }
        }

    });

// Allow participant to delete coins
d3.selectAll('.deleter')
    .on('click',function(d){
        var del = d3.select(this);
        var vals = dist_tracker["bin-"+del.attr('id').split('-')[1]].coins;

        if (vals.length > 0){
            var last_coin = vals[vals.length - 1];
            
            d3.select('#' + last_coin).remove();

            dist_tracker["bin-"+del.attr('id').split('-')[1]].coins.splice(-1, 1);
            dist_tracker["bin-"+del.attr('id').split('-')[1]].currentY += coin_height;
			
			// Add token deletion to order
			coin_order.push("DEL" + del.attr('id'));
			
            // Increment tokens used
            used_tokens -= 1;

            // Update plot title
            plot_title.text('Tokens left: ' + (tokens - used_tokens));
        }

        if (used_tokens !== tokens){
          end_g.attr('opacity', 0);
        }

    });

// Define function for returning distribution data
function return_data(){
	if (used_tokens === tokens){
        // Create stash for tokens
        let arr = [];

        // Count tokens in each bin
        for (const [key, value] of Object.entries(dist_tracker)) {
            arr.push((key.split('-')[1], value['coins'].length));
        }

        // Record perceived distribution
        Qualtrics.SurveyEngine.setEmbeddedData('dist_response', arr.toString());
		
        // Record coin-placement order
        Qualtrics.SurveyEngine.setEmbeddedData('dist_response_order', coin_order.toString());

        // Advance to next page
        (function(){that.clickNextButton();}).delay(0.2);
	}
}